<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title>红安人聊天室</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="${CONTEXT_PATH}/_back/CloudAdmin/css/cloud-admin.css">
    <style>
        p{text-align: center}
        </style>
</head>
<body>
<h1>欢迎欢迎</h1>

<hr>
    <div class="form-group">
        <label for="text">在此处填入消息</label>
        <i class="fa fa-envelope"></i>
        <input type="text" class="form-control" id="text">
    </div>
<button class="btn  btn-blue" onclick="send()">发送</button>
<button class="btn  btn-red" onclick="closeWebSocket()">暂停</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    //ws://echo.websocket.org
    if('WebSocket' in window){
        websocket = new WebSocket("ws://www.0713jc.com/socket");
    }else{
        alert('不支持websocket');
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("链接出错");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(){
        setMessageInnerHTML("<h3>欢迎加入聊天室！更多功能正在开发</h3>");
    };

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    };

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("已关闭");
    };

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    };

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += '<p>'+innerHTML + '</p>';
    }

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>